<script setup lang="ts">
import { reactive, computed } from 'vue'
import { ElButton, ElForm, ElRow, ElInput, ElInputNumber, ElSwitch } from 'element-plus'
// import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'
import { createRoomFloorsApi, updateRoomFloorsApi, getRoomFloorsDetailApi } from '@/api/room-floor'
import { RoomFloor } from '@/api/room-floor/types'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { FormItem } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useCreate } from '@/hooks/web/useCreate'
import { onMounted } from 'vue'

const { push } = useRouter()

const { required } = useValidator()

const back = () => {
  push('/settings/room-floor')
}

const instance: RoomFloor = reactive(new RoomFloor())
const route = useRoute()

const { elFormRef, openMode, save, loading } = useCreate({
  instance,
  route,
  afterSave: back,
  createApi: createRoomFloorsApi,
  updateApi: updateRoomFloorsApi
})

const rules = reactive({
  code: [required('请填写代码')],
  name: [required('请填写描述')]
})

const title = computed(() => {
  return openMode.value === 'CREATE' ? '添加楼层' : '编辑楼层'
})

onMounted(async () => {
  if (openMode.value === 'UPDATE') {
    const { data } = await getRoomFloorsDetailApi(route.params.id as string)
    instance.init(data)
  }
})
</script>

<template>
  <ContentDetailWrap :title="title" @back="back">
    <template #right>
      <ElButton type="primary" :loading="loading" @click="save"> 保存 </ElButton>
    </template>

    <ElForm ref="elFormRef" :model="instance" label-width="100px" :rules="rules">
      <ElRow style="max-width: 450px; margin: 0 auto">
        <FormItem :col-props="{ span: 24 }" label="代码" prop="code">
          <ElInput v-model="instance.code" maxlength="50" :disabled="openMode === 'UPDATE'" />
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="描述" prop="name">
          <ElInput v-model="instance.name" maxlength="200" />
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label-width="100px" prop="disabled">
          <ElSwitch v-model="instance.disabled" active-text="禁用" />
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="序号" prop="sequence">
          <ElInputNumber v-model="instance.sequence" controls-position="right" :min="1" />
        </FormItem>
      </ElRow>
    </ElForm>
  </ContentDetailWrap>
</template>
